/*
 * COPYRIGHT. ShenZhen JiMi Technology Co., Ltd. 2020.
 * ALL RIGHTS RESERVED.
 *
 * No part of this publication may be reproduced, stored in a retrieval system, or transmitted,
 * on any form or by any means, electronic, mechanical, photocopying, recording, 
 * or otherwise, without the prior written permission of ShenZhen JiMi Network Technology Co., Ltd.
 *
 * Amendment History:
 * 
 * Date                   By              Description
 * -------------------    -----------     -------------------------------------------
 * 2020年2月18日    Zhao Haiming         Create the class
 * http://www.jimilab.com/
*/

package com.futuremap.ws.handler;

import java.util.concurrent.atomic.AtomicInteger;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.futuremap.ws.bean.APIContent;
import com.futuremap.ws.bean.WebSocketBean;
import com.futuremap.ws.constant.CommonConstant;
import com.futuremap.ws.service.WebSocketService;
import com.futuremap.ws.util.ChannelSupervise;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http.HttpVersion;
import io.netty.handler.codec.http.websocketx.CloseWebSocketFrame;
import io.netty.handler.codec.http.websocketx.PingWebSocketFrame;
import io.netty.handler.codec.http.websocketx.PongWebSocketFrame;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketServerHandshaker;
import io.netty.handler.codec.http.websocketx.WebSocketServerHandshakerFactory;
import io.netty.util.CharsetUtil;

/**
 * @FileName WebSocketServerHandler.java
 * @Description: 
 *
 * @Date 2020年2月18日 下午5:30:06
 * @author Zhao Haiming
 * @version 1.0
 */
@Service
@ChannelHandler.Sharable
public class WebSocketServerHandler extends SimpleChannelInboundHandler<Object> {
    private static final Logger logger = LoggerFactory.getLogger(WebSocketServerHandler.class.getName());

    private WebSocketServerHandshaker handshaker;
    
    @Autowired
    private WebSocketService webSocketService;

    private static AtomicInteger connAtomic = new AtomicInteger(0);

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
        
        if (msg instanceof FullHttpRequest){
        	logger.info("收到http消息："+msg);
            //以http请求形式接入，但是走的是websocket
            handleHttpRequest(ctx, (FullHttpRequest) msg);
        }else if (msg instanceof  WebSocketFrame){
        	logger.info("收到ws消息："+msg);
            //处理websocket客户端的消息
            handlerWebSocketFrame(ctx, (WebSocketFrame) msg);
        }
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        //添加连接
        int count = connAtomic.incrementAndGet();
        logger.info("客户端加入连接：{};当前连接数={}", ctx.channel(), count);
        //routeLoginIpCache.setPaasRoute(key, field, value);
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        //断开连接
        String useId = ctx.channel().attr(CommonConstant.userIdAK).get();
        if(StringUtils.isNotBlank(useId))
        {
        	ChannelSupervise.unRegisterChannel(useId, ctx.channel());
        }
        int count = connAtomic.decrementAndGet();
        logger.info("客户端断开连接：{};当前连接数={}", ctx.channel(), count);
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.flush();
    }
    
    private void handlerWebSocketFrame(ChannelHandlerContext ctx, WebSocketFrame frame){
        // 判断是否关闭链路的指令
        if (frame instanceof CloseWebSocketFrame) {
            handshaker.close(ctx.channel(), (CloseWebSocketFrame) frame.retain());
            return;
        }
        // 判断是否ping消息
        if (frame instanceof PingWebSocketFrame) {
            ctx.channel().write(
                    new PongWebSocketFrame(frame.content().retain()));
            return;
        }
        // 本例程仅支持文本消息，不支持二进制消息
        if (!(frame instanceof TextWebSocketFrame)) {
            logger.debug("本例程仅支持文本消息，不支持二进制消息");
            throw new UnsupportedOperationException(String.format(
                    "%s frame types not supported", frame.getClass().getName()));
        }
        
        //获取消息
        String request = ((TextWebSocketFrame) frame).text();
        logger.info("服务端收到：" + request);
        WebSocketBean msgBean = JSON.parseObject(request, WebSocketBean.class);
        
        //组装通道中的基本信息
        TextWebSocketFrame tws = webSocketService.executeMsg(msgBean);
        logger.info("服务端发送回客户端：appId=" + ctx.channel().attr(CommonConstant.appIdAK).get()+";content="+tws.text());
        // 返回【谁发的发给谁】
        ctx.channel().writeAndFlush(tws);
    }
    /**
     * 唯一的一次http请求，用于创建websocket
     * */
    private void handleHttpRequest(ChannelHandlerContext ctx,
                                   FullHttpRequest req) {
        //要求Upgrade为websocket，过滤掉get/Post
        if (!req.decoderResult().isSuccess()
                || (!"websocket".equals(req.headers().get("Upgrade")))) {
            //若不是websocket方式，则创建BAD_REQUEST的req，返回给客户端
            sendHttpResponse(ctx, req, new DefaultFullHttpResponse(
                    HttpVersion.HTTP_1_1, HttpResponseStatus.BAD_REQUEST));
            return;
        }

    	WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory(
                "ws://localhost:8889/websocket", null, false);
        handshaker = wsFactory.newHandshaker(req);
        if (handshaker == null) {
            WebSocketServerHandshakerFactory
                    .sendUnsupportedVersionResponse(ctx.channel());
        } else {
            handshaker.handshake(ctx.channel(), req);
        }
        
        String uri = req.uri();
        WebSocketBean wsBean = webSocketService.getParamFromUri(uri);
        APIContent paramResult = webSocketService.checkParam(wsBean);
        if(paramResult.getCode() != 0)
        {
        	logger.error("参数错误3秒后关闭连接:"+JSON.toJSONString(paramResult));
        	TextWebSocketFrame tws = new TextWebSocketFrame(JSON.toJSONString(paramResult));
        	ctx.channel().writeAndFlush(tws);
        	try {
				Thread.sleep(3000);
			} catch (InterruptedException e) {
				logger.error("handleHttpRequest Thread sleep error");
			}
        	ctx.channel().close();
        }
        else
        {
        	ctx.channel().attr(CommonConstant.appIdAK).set(wsBean.getAppId());
        	ctx.channel().attr(CommonConstant.userIdAK).set(wsBean.getUserId());
        	//注册ws的channel，收到设备主动上报的信息发送给客户端使用
        	ChannelSupervise.registerChannel(wsBean.getUserId(), ctx.channel());

        	TextWebSocketFrame tws = new TextWebSocketFrame(JSON.toJSONString(paramResult));
        	ctx.channel().writeAndFlush(tws);
        }
    }
    /**
     * 拒绝不合法的请求，并返回错误信息
     * */
    private static void sendHttpResponse(ChannelHandlerContext ctx,
                                         FullHttpRequest req, DefaultFullHttpResponse res) {
        // 返回应答给客户端
//        if (res.status().code() != 200) {
//            ByteBuf buf = Unpooled.copiedBuffer(res.status().toString(),
//                    CharsetUtil.UTF_8);
//            res.content().writeBytes(buf);
//            buf.release();
//        }
    	if (res.status().code() != 200) {
            ByteBuf buf = Unpooled.copiedBuffer(res.status().toString(),
                    CharsetUtil.UTF_8);
            res.content().writeBytes(buf);
            buf.release();
        }
        ChannelFuture f = ctx.channel().writeAndFlush(res);
        // 如果是非Keep-Alive，关闭连接
        if (res.status().code() != 200) {
            f.addListener(ChannelFutureListener.CLOSE);
        }
    }
    
    
}